package org.agridata.akvisualization.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.agridata.akvisualization.doMain.entity.Brucellosis;
import org.agridata.akvisualization.doMain.entity.Pestilence;
import org.agridata.akvisualization.doMain.vo.OriginVo;
import org.agridata.akvisualization.doMain.vo.PestilenceVo;
import org.agridata.akvisualization.mapper.DiseaseSurveillanceMapper;
import org.agridata.akvisualization.result.Result;
import org.agridata.akvisualization.service.DiseaseSurveillanceService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class DiseaseSurveillanceServiceImpl implements DiseaseSurveillanceService {
    @Autowired
    private DiseaseSurveillanceMapper mapper;

    @Override
    public Result importDiseaseSurveillance(List<Pestilence> memberList, String dates,String user) {
        int successCount = 0;
        int failureCount = 0;
        try {
            List<Pestilence> pestilence = mapper.selectPestilenceByDates(dates);
            if (pestilence.size() > 0) {
                mapper.deletePestilence(pestilence);
            }
            for (Pestilence pestilenceVo : memberList) {
                try {
                    pestilenceVo.setDates(dates);
                    pestilenceVo.setUser(user);
                    mapper.insertPestilence(pestilenceVo);
                    successCount++;
                } catch (Exception e) {
                    failureCount++;
                    e.printStackTrace();
                }
            }


            return Result.ok("成功：" + successCount + "条" + "，" + "失败" + failureCount + "条");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("出现异常");
        }
    }

    @Override
    public Result diseaseListPage(String pestilence, Long pageNo, Long pageSize) {
        try {
            Page<PestilenceVo> page = new Page<>(pageNo, pageSize);
            Page<PestilenceVo> pestilencePage = mapper.selectDiseaseListPage(page, pestilence);
            return Result.ok(pestilencePage);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("出现异常！");
        }
    }

    @Override
    public Result barChartByMonth(Integer type) {
        List<Map<String, Object>> pestilenceVoList = new ArrayList<>();
        List<Map<String, Object>> map = new ArrayList<>();
        Map<String, List<Brucellosis>> bruMap = new HashMap<>();
        try {
            if (type != 3) {
                //转化数据
                pestilenceVoList = mapper.selectPestilenceVoList(type);
                map = groupByMonth(pestilenceVoList);
//                String[] bing = {"非洲猪瘟", "口蹄疫", "猪瘟", "小反刍兽疫", "禽流感H7", "禽流感H5", "新城疫"};
//                if (type == 1){
//                    bing = new String[]{"非洲猪瘟", "口蹄疫", "猪瘟", "小反刍兽疫","禽流感", "新城疫"};
//                }
//                String[] finalBing = bing;
//                map.forEach((key, value) -> {
//                    // 如果该月份的列表为空，则添加默认值
//                    if (value.isEmpty()) {
//                        for (String s : finalBing) {
//                            Map<String, Object> maps = new HashMap<>();
//                            maps.put("quantity", 0);
//                            maps.put("month", key);
//                            maps.put("pestilence", s);
//                            value.add(maps);
//                        }
//                    } else {
//                        // 如果该月份的列表不为空，则检查是否存在特定疾病，如果不存在则添加默认值
//                        List<String> pestilences = new ArrayList<>();
//                        for (Map<String, Object> objectMap : value) {
//                            String pestilence = objectMap.get("pestilence").toString();
//                            pestilences.add(pestilence);
//                        }
//                        for (String s : finalBing) {
//                            if (!pestilences.contains(s)) {
//                                Map<String, Object> maps = new HashMap<>();
//                                maps.put("quantity", 0);
//                                maps.put("month", key);
//                                maps.put("pestilence", s);
//                                value.add(maps);
//                            }
//                        }
//                    }
//                });
            } else {
                //转化数据
                List<Brucellosis> brucelloses = mapper.selectBrucellosisList();
                bruMap = groupByYear(brucelloses);
                return Result.ok(bruMap);
            }



            return Result.ok(map);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("出现异常");
        }
    }

    @Override
    public Result importBrucellosis(List<Brucellosis> memberList, String category,String user) {
        int successCount = 0;
        int failureCount = 0;
        try {
            List<Brucellosis> brucellosisList = mapper.selectBrucellosisByCategory(category);
            if (brucellosisList.size() > 0) {
                mapper.deleteBrucellosis(brucellosisList);
            }
            for (Brucellosis brucellosis : memberList) {
                try {
                    brucellosis.setCategory(category);
                    brucellosis.setUser(user);
                    mapper.insertBrucellosis(brucellosis);
                    successCount++;
                } catch (Exception e) {
                    failureCount++;
                    e.printStackTrace();
                }
            }


            return Result.ok("成功：" + successCount + "条" + "，" + "失败" + failureCount + "条");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("出现异常");
        }

    }

    @Override
    public Result brucellosisList() {
        try {
            List<Brucellosis> list = mapper.selectBrucellosisList();
            return Result.ok(list);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("出现异常");
        }
    }

    @Override
    public Result homePageByNewDate() {
        List<Map<String, Object>> list = mapper.selectHomePageByNewDate();
        Map<String, List<Map<String, Object>>> map = new HashMap<>();
        try {
            for (Map<String, Object> objectMap : list) {
                String pestilence = objectMap.get("pestilence").toString();
                //将字段中中文转为拼音
                String pinyin = toPinyin(pestilence);
                // 检查是否已存在具有相同类型的疾病的列表
                if (map.containsKey(pinyin)) {
                    // 如果存在，则将数据添加到现有列表中
                    map.get(pinyin).add(objectMap);
                } else {
                    // 如果不存在，则创建一个新的列表，并将数据添加到其中
                    List<Map<String, Object>> tempList = new ArrayList<>();
                    tempList.add(objectMap);
                    map.put(pinyin, tempList);
                }
            }
            System.out.println(map);
            return Result.ok(map);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("出现异常");
        }
    }

    @Override
    public Result diseaseListJiLu(String date, Long pageNo, Long pageSize) {
        try {
            Page<PestilenceVo> page = new Page<>(pageNo, pageSize);
            Page<PestilenceVo> pestilencePage = mapper.selectDiseaseListJiLu(page,date);
            return Result.ok(pestilencePage);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("出现异常");
        }
    }

    @Override
    public Result brucellosisJiLu(String date, Long pageNo, Long pageSize) {
        try {
            Page<PestilenceVo> page = new Page<>(pageNo, pageSize);
            Page<PestilenceVo> pestilencePage = mapper.selectBrucellosisJiLu(page,date);
            return Result.ok(pestilencePage);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("出现异常");
        }
    }

    private List<Map<String, Object>> groupByMonth(List<Map<String, Object>> pestilenceVoList) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (Map<String, Object> map : pestilenceVoList) {
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("pestilence", map.get("pestilence"));
            List<Integer> annualData = new ArrayList<>();
            annualData.add(Integer.parseInt(map.get("jan").toString()));
            annualData.add(Integer.parseInt(map.get("feb").toString()));
            annualData.add(Integer.parseInt(map.get("mar").toString()));
            annualData.add(Integer.parseInt(map.get("apr").toString()));
            annualData.add(Integer.parseInt(map.get("may").toString()));
            annualData.add(Integer.parseInt(map.get("jun").toString()));
            annualData.add(Integer.parseInt(map.get("jul").toString()));
            annualData.add(Integer.parseInt(map.get("aug").toString()));
            annualData.add(Integer.parseInt(map.get("sept").toString()));
            annualData.add(Integer.parseInt(map.get("oct").toString()));
            annualData.add(Integer.parseInt(map.get("nov").toString()));
            annualData.add(Integer.parseInt(map.get("dec").toString()));

            resultMap.put("AnnualData", annualData);
            resultList.add(resultMap);

        }





        // 初始化包含所有十二个月的键（英文缩写）
//        String[] months = {"jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"};
//        for (String month : months) {
//            dataMap.put(month, new ArrayList<>());
//        }
//
//        // 将查询结果放入 Map 中
//        for (Map<String, Object> row : pestilenceVoList) {
////            String disease = row.get("pestilence");
//            String month = row.get("month").toString();
//            List<Map<String, Object>> diseaseList = dataMap.get(month);
//            if (diseaseList != null) {
//                diseaseList.add(row);
//            }
//        }



        return resultList;
    }
    // 辅助方法：获取月份的英文缩写
    private static String getMonthName(int month) {
        String[] months = {"jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"};
        return months[month - 1];
    }
    private Map<String, List<Brucellosis>> groupByYear(List<Brucellosis> brucelloses) {
        Map<String, List<Brucellosis>> dataMap = new HashMap<>();
        for (Brucellosis brucellose : brucelloses) {
            String category = brucellose.getCategory();
            //将字段中中文转为拼音
            String pinyin = toPinyin(category);
            // 检查是否已存在具有相同类型的疾病的列表
            if (dataMap.containsKey(pinyin)) {
                // 如果存在，则将数据添加到现有列表中
                dataMap.get(pinyin).add(brucellose);
            } else {
                // 如果不存在，则创建一个新的列表，并将数据添加到其中
                List<Brucellosis> tempList = new ArrayList<>();
                tempList.add(brucellose);
                dataMap.put(pinyin, tempList);
            }
        }
        return dataMap;
    }

    public static String toPinyin(String chinese) {
        String pinyinStr = "";
        char[] newChar = chinese.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < newChar.length; i++) {
            if (newChar[i] > 128) {
                try {
                    pinyinStr += PinyinHelper.toHanyuPinyinStringArray(newChar[i], defaultFormat)[0];
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                pinyinStr += newChar[i];
            }
        }
        return pinyinStr;
    }
}
